from django.contrib import messages
from django.shortcuts import redirect, render
from django.contrib.auth import authenticate, login, logout
from django.views.generic.base import View
from django.views.generic import FormView
from .forms import SignUpForm, SignInForm
from .models import User
from book.models import Book
from cart.models import Cart


class SignUpView(FormView):
    template_name = 'user/signup.html'
    form_class = SignUpForm
    success_url = '/'

    def form_valid(self, form):
        user = form.save()
        login(self.request, user)
        return super().form_valid(form)


class SignInView(FormView):
    template_name = 'user/signin.html'
    form_class = SignInForm
    success_url = '/'

    def form_valid(self, form):
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            login(self.request, user)
            return super().form_valid(form)
        else:
            messages.error(self.request, "用户名或密码不正确!")


class UserDetailView(View):
    def get(self, request, user_id):
        user = User.objects.get(pk=user_id)
        trades = Cart.objects.filter(user_id=user_id, paid=True)
        return render(
            request,
            'user/detail.html',
            {
                'user': user,
                'trades': trades,
            }
        )


class LogoutView(View):
    def get(self, request):
        logout(request)
        return redirect('/')
